#include "CAN.h"
#include "string.h"

void MY_CAN_Init(){
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);

	CAN_InitTypeDef CAN_InitStruct;
	// 42000/(1+7+6)/6
	CAN_InitStruct.CAN_BS1 = CAN_BS1_7tq;
	CAN_InitStruct.CAN_BS2 = CAN_BS2_6tq;
	CAN_InitStruct.CAN_Prescaler = 6;
	CAN_InitStruct.CAN_SJW = 1;
	CAN_InitStruct.CAN_Mode = CAN_Mode_LoopBack;
	CAN_InitStruct.CAN_NART = DISABLE;
	CAN_InitStruct.CAN_ABOM = DISABLE;
	CAN_InitStruct.CAN_AWUM = DISABLE;
	CAN_InitStruct.CAN_RFLM = DISABLE;
	CAN_InitStruct.CAN_TTCM = DISABLE;
	CAN_InitStruct.CAN_TXFP = DISABLE;
	CAN_Init(CAN1,&CAN_InitStruct);
	
	CAN_FilterInitTypeDef CAN_Filter;
	CAN_Filter.CAN_FilterActivation = ENABLE;
	CAN_Filter.CAN_FilterFIFOAssignment = CAN_FIFO0;
	CAN_Filter.CAN_FilterIdHigh = 0x00;
	CAN_Filter.CAN_FilterIdLow = 0x00;
	CAN_Filter.CAN_FilterMaskIdHigh = 0x00;
	CAN_Filter.CAN_FilterMaskIdLow = 0x00;
	CAN_Filter.CAN_FilterMode = CAN_Mode_LoopBack;
	CAN_Filter.CAN_FilterNumber = 0;
	CAN_Filter.CAN_FilterScale = CAN_FilterScale_32bit;
	CAN_FilterInit(&CAN_Filter);
	
	// RX/TX 
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11|GPIO_Pin_12;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource3,GPIO_AF_CAN1);
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource4,GPIO_AF_CAN1);
	
}

void can_send(char* data){
	// test
	CanTxMsg CanMsg;
	CanMsg.DLC = 8;
	CanMsg.IDE = CAN_Id_Standard;
	CanMsg.StdId = 0x17;
	CanMsg.RTR = CAN_RTR_DATA;
	
	for(int i=0;i<strlen(data);i+=4){
		CanMsg.Data[0] = data[i];
		CanMsg.Data[1] = data[i+1];
		CanMsg.Data[2] = data[i+2];
		CanMsg.Data[3] = data[i+3];
	}

	CAN_Transmit(CAN1,&CanMsg);
}
